<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>键盘事件</title>
</head>

<body>
    <input type="text" name="account" value="" id="account">
    <input type="password" name="password" value="" id="password">
    <button id="submit">登录</button>
</body>

</html>
<script>
    let account = window.document.querySelector('#account');
    let password = window.document.querySelector('#password');
    let submit = window.document.querySelector('#submit');

    submit.addEventListener('click', commit);

    function commit(e) {
        if ("" == account.value.trim()) {
            window.alert('帐号不能为空');
            account.focus();
            return;
        } else if ("" == password.value.trim()) {
            window.alert('密码不能为空');
            password.focus();
            return;
        } else {
            window.console.log('帐号>>>' + account.value.trim());
            window.console.log('密码>>>' + password.value.trim());
        }
    }
    window.document.addEventListener('keyup', function(e) {
        if (e.keyCode == 13) {
            commit();
        }
    });
</script>